package com.zrrd.yt.product.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.yt.model.product.BaseAttrInfo;
import com.zrrd.yt.model.product.BaseAttrValue;
import com.zrrd.yt.product.mapper.BaseAttrInfoMapper;
import com.zrrd.yt.product.mapper.BaseAttrValueMapper;
import com.zrrd.yt.product.service.BaseAttrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author HongyueYang
 */
@Service
public class BaseAttrServiceImpl extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo> implements BaseAttrService {

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    //根据分类id查询平台属性值以及属性值
    @Override
    public List<BaseAttrInfo> selectBaseAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.selectBaseAttrInfoList(category1Id, category2Id, category3Id);
    }

    //添加 修改平台属性
    @Override
    @Transactional
    public void saveBaseAttrInfo(BaseAttrInfo baseAttrInfo) {

        //判断添加还是修改
        if (baseAttrInfo.getId() != null) {
            this.updateById(baseAttrInfo);
        } else {
            //保存平台属性信息
            this.save(baseAttrInfo);
        }
        //根据属性id作为条件 删除属性值表对应的数据
        QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_id", baseAttrInfo.getId());
        baseAttrValueMapper.delete(wrapper);

        //获取传递来的属性值集合
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        if (attrValueList != null && attrValueList.size() > 0) {
            //添加属性值
            for (BaseAttrValue baseAttrValue : attrValueList) {
                //设置属性id
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                //保存属性值
                baseAttrValueMapper.insert(baseAttrValue);

            }
        }
    }

    //根据属性id查询属性值列表
    @Override
    public List<BaseAttrValue> getAttrInfo(Long attrId) {
        //根据属性id获取属性值集合
        QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_id", attrId);
        List<BaseAttrValue> baseAttrValueList = baseAttrValueMapper.selectList(wrapper);
        return baseAttrValueList;
    }

    @Override
    public List<BaseAttrInfo> selectBaseAttrInfoListBySkuId(Long skuId) {
        return baseAttrInfoMapper.selectBaseAttrInfoListBySkuId(skuId);
    }
}
